package cn.com.server.service.impl;

import cn.com.server.dao.GroupRoleDao;
import cn.com.server.dao.RoleDao;
import cn.com.server.entity.GroupRole;
import cn.com.server.entity.Role;
import cn.com.server.service.RoleService;
import cn.com.server.extend.model.RoleEntityModel;
import cn.com.server.extend.model.RoleModel;
import cn.com.server.extend.view.RoleView;

import java.sql.SQLDataException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author qing
 * @since 2017-11-20
 */
@Service
public class RoleServiceImp implements RoleService {
	
	@Autowired
	private RoleDao dao;
	
	@Autowired 
	private GroupRoleDao groupRoleDao;
	
	@Override
	public List<Role> selectByUserId(Long id) {
		return dao.selectByUserId(id);
	}
	
	@Override
	public List<Role> selectByGroupId(Long groupId){
		return dao.selectByGroupId(groupId);
	}
	
	@Override
	public Page<RoleView> selectRoleViewList(RoleModel model){
		PageHelper.startPage(model.getPage(), model.getLimit());
		Page<RoleView> pageData = dao.selectRoleViewList(model);
		return pageData;
	}
	
	@Override
	public int insert(Role entity) {
		return dao.insert(entity);
	}
	
	@Override
	public int update(Role entity) {
		return dao.update(entity);
	}
	
	@Override
	@Transactional
	public int insertRoleAndRoleGroup(RoleEntityModel model){
		Role entity = model;
		dao.insert(entity);
		GroupRole groupRole = new GroupRole();
		groupRole.setRoleId(entity.getId());
		groupRole.setGroupId(model.getGroupId());
		return groupRoleDao.insert(groupRole);
	}
	
	@Override
	@Transactional
	public int updateRoleAndRoleGroup(RoleEntityModel model){
		Role entity = model;
		dao.update(entity);
		GroupRole groupRole = new GroupRole();
		groupRole.setRoleId(entity.getId());
		groupRole.setGroupId(model.getGroupId());
		groupRoleDao.updateAndDelete(groupRole);
		return groupRoleDao.insert(groupRole);
	}
	
	@Override
	@Transactional
	public int deleteRoleAndAllByRoleIds(String ids) throws SQLDataException{
		String[] idArr = ids.split(",");
		int i = 0;
		for(String id:idArr) {
			i = i+dao.deleteRoleAndAllByRoleId(Long.valueOf(id));
		}
		if(i<1) {
			throw new SQLDataException();
		}
		return i;
	}
}
